#include "logpostback.h"
#include "machineutil.h"
#include "enetwork.h"
#include "mylogger.h"

using namespace ns_yht;
LogPostback::LogPostback()
{
    m_pNetworkAccessManager = new QNetworkAccessManager(this);
}

LogPostback::~LogPostback()
{
}

/**
 * @brief
 *
 * @param mtype 这个mtype和AlertType不一样，这是化传明后台定义的，告警类型（1:进入风险区   2:驶出风险区  3:会遇AIS   4:会遇风险解除）
 * @param mtime
 * @param minfo
 */
void LogPostback::onPostlog_alert(int mtype, qint64 mtime, int minfo)
{
    // QString url = QString("http://restapi.ehanghai.cn/xxyc-api/login/%1/%2").arg(MachineUtil::machineCode(), "m_softwareCode");
    // QNetworkReply *reply = ENetwork::Post(m_pNetworkAccessManager,, {}, {}, false);

    qInfo() << "onPostlog_alert ------------- " << mtype << mtime << minfo;

    QJsonObject obj;
    obj.insert("machineCode", MachineUtil::machineCode());
    obj.insert("type", mtype);
    obj.insert("createDate", mtime * 1000);
    obj.insert("targetInfo", QString::number(minfo));

    QNetworkReply *reply = ENetwork::PostWithJson(m_pNetworkAccessManager, QJsonDocument(obj).toJson(), "http://restapi.ehanghai.cn/xxyc-api/alarmLog/v1/add", {}, {}, true);

    if (reply != nullptr)
    {
        connect(reply, &QNetworkReply::finished, this, [=]
                { onReplyFinished_alert(reply); });
        // 添加错误处理
        connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::errorOccurred),
                this, [this, reply](QNetworkReply::NetworkError code)
                {
                    if (GLOG)
                        GLOG->error("Network error in postlog-alert: {}", code);
                    reply->deleteLater(); });
    }
    else
    {
        if (GLOG)
            GLOG->error("Failed to create network request in postlog-alert");
    }
}

/**
 * @brief
 *
 * @param mtype 这个mtype和AlertType不一样，这是化传明后台定义的，告警类型（1:开机  3:AIS断开    2是心跳异常）
 * @param mtime
 */
void LogPostback::onPostlog_system(int mtype, qint64 mtime)
{
    qInfo() << "onPostlog_system ------------- " << mtype << mtime;
    QJsonObject obj;
    obj.insert("machineCode", MachineUtil::machineCode());
    obj.insert("type", mtype);
    obj.insert("createDate", mtime * 1000);
    QNetworkReply *reply = ENetwork::PostWithJson(m_pNetworkAccessManager, QJsonDocument(obj).toJson(), "http://restapi.ehanghai.cn/xxyc-api/sysLog/v1/add", {}, {}, true);
    if (reply != nullptr)
    {
        connect(reply, &QNetworkReply::finished, this, [=]
                { onReplyFinished_system(reply); });
        // 添加错误处理
        connect(reply, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::errorOccurred),
                this, [this, reply](QNetworkReply::NetworkError code)
                {
                            if (GLOG)
                                GLOG->error("Network error in postlog-system: {}", code);
                            reply->deleteLater(); });
    }
    else
    {
        if (GLOG)
            GLOG->error("Failed to create network request in postlog-system");
    }
}

void LogPostback::onReplyFinished_alert(QNetworkReply *reply)
{
    if (ENetwork::checkReplyError(reply))
    {
        if (GLOG)
            GLOG->error("Failed to post log-alert");
    }
    else
    {
        // QJsonObject root = QJsonDocument::fromJson(reply->readAll()).object();
        // if (ENetwork::checkRootError(root, "postlog-alert"))
        qInfo() << "Succeed to post log-alert" << reply->readAll();
        if (GLOG)
            GLOG->info("Succeed to post log-alert");
    }
    reply->deleteLater();
}

void LogPostback::onReplyFinished_system(QNetworkReply *reply)
{
    if (ENetwork::checkReplyError(reply))
    {
        if (GLOG)
            GLOG->error("Failed to post log-system");
    }
    else
    {
        // QJsonObject root = QJsonDocument::fromJson(reply->readAll()).object();
        // if (ENetwork::checkRootError(root, "postlog-system"))
        qInfo() << "Succeed to post log-system" << reply->readAll();
        if (GLOG)
            GLOG->info("Succeed to post log-system");
    }
    reply->deleteLater();
}

void LogPostback::onPostHeartbeat()
{
    if (GLOG)
        GLOG->info("startHeartBeat......");
    QString url = QString("http://restapi.ehanghai.cn/xxyc-api/login/heartbeat?machineCode=%1&softwareCode=%2").arg(MachineUtil::machineCode(), "Black-Main-Arm");
    QNetworkReply *reply = ENetwork::Get(m_pNetworkAccessManager, url, "", "", false);
    connect(reply, &QNetworkReply::finished, this, [=]
            { onReplyFinished_heartbeat(reply); });
}

void LogPostback::onReplyFinished_heartbeat(QNetworkReply *reply)
{
    if (ENetwork::checkReplyError(reply))
    {
        if (GLOG)
            GLOG->info("requestHeartBeat Finished 1. code:{} name:{}  result: false");
        // emit heartBeatFinished(false);
        return;
    }
    const QJsonDocument &jsonDocument = QJsonDocument::fromJson(reply->readAll());
    reply->deleteLater();
    if (!jsonDocument.isNull())
    {
        const QJsonObject &rootObj = jsonDocument.object();
        if (!rootObj.value("success").toBool())
        {
            if (GLOG)
                GLOG->info("requestHeartBeat Finished 2. code:{} name:{}  result: false");
            // emit heartBeatFinished(false);
            return;
        }
        else
        {
            if (GLOG)
                GLOG->info("requestHeartBeat Finished 3. code:{} name:{}  reason:{} result: true");
            // emit heartBeatFinished(true);
            return;
        }
    }
}
